package com.zyb.system.shop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zyb.base.service.impl.BaseServiceImpl;
import com.zyb.constans.BaseConstants;
import com.zyb.system.employee.domain.Employee;
import com.zyb.system.employee.mapper.EmployeeMapper;
import com.zyb.system.shop.domain.Shop;
import com.zyb.system.shop.mapper.ShopAuditLogMapper;
import com.zyb.system.shop.mapper.ShopMapper;
import com.zyb.system.shop.query.ShopQuery;
import com.zyb.system.shop.service.IShopService;
import com.zyb.utils.AuthService;
import com.zyb.utils.BusinessException;
import com.zyb.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Arvin
 * @since 2023-01-07
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private AuthService authService;

    @Override
    public void add(Shop shop) {
        ShopQuery shopQuery = new ShopQuery();
        shopQuery.setName(shop.getName());
        Long count = shopMapper.queryCount(shopQuery);
        //进行判断
        if(shop.getName() == null){
            throw new BusinessException("店铺名不能为为空");
        }
        //判断用户名是否存在
        if(count > 0){
            throw new BusinessException("该[ "+shop.getName()+" ]'店铺名已存在,请重新输入");
        }
        if(shop.getTel() == null){
            throw new BusinessException("联系方式不能为为空");
        }
        if(shop.getAddress() == null){
            throw new BusinessException("地址不能为为空");
        }
        //int a=1/0;
        //补充缺失数据
        shop.setRegisterTime(new Date());//当前时间
        shop.setState(BaseConstants.Shop.STATE_WAIT_AUTID);//设置为待审核状态
        //不为真就抛出该异常
        if(!authService.authentication(shop.getName())){
            throw new BusinessException("您的店铺名存在违规信息，请重新填写");
        }

        //获取管理员
        Employee admin = shop.getAdmin();
        //设置商家状态在待激活
        admin.setState(BaseConstants.Employee.STATE_WAIT_ACTIVE);
        //注册的管理员信息添加到员工表 就能获取员工id
        employeeMapper.save(admin);
        //获取管理员id 将员工设置成管理员
        shop.setAdminId(admin.getId());
        //保存管理员Id到数据库 就能获取商品id
        shopMapper.save(shop);
        //获取店铺id 商店id设置给员工
        admin.setShop_id(shop.getId());
        //保存数据
        employeeMapper.update(admin);

    }

    @Override
    public void activation(Long shopId) {
        Shop shop = shopMapper.loadById(shopId);
        shop.setState(BaseConstants.Shop.STATE_ACTIVE_SUCCESS);
        Long adminId = shop.getAdminId();
        Employee employee = employeeMapper.loadById(adminId);
        employee.setState(BaseConstants.Employee.STATE_NORMAL);
        employeeMapper.update(employee);
    }
}
